function previewImage(input) {
    const preview = document.getElementById('preview');
    const file = input.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function (e) {
            preview.src = e.target.result;
            preview.style.display = 'block';
            input.parentNode.querySelector('.plus-icon').style.display = 'none';
        };
        reader.readAsDataURL(file);
    }
}

function submitCategory() {
    const submitButton = document.getElementById("submitcat");
    const id = submitButton.getAttribute("data-category-id");
    const url = id ? `/end/editCategory/${id}` : document.getElementById("addCategoryUrl").value;

    const name = document.getElementById('categoryname').value.trim();
    const desc = document.getElementById('categorycontent').value.trim();
    const file = document.getElementById('coverUpload').files[0];

    if (!name) {
        alert('名称不能为空！');
        return;
    }

    const formData = new FormData();
    formData.append('name', name);
    formData.append('desc', desc);

    if (!id || file) {
        formData.append('cover', file);
    }

    fetch(url, {
        method: 'POST',
        body: formData,
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('网络响应失败');
        }
        return response.json();  // 👈 期待后端返回 JSON 格式
    })
    .then(result => {
        if (result.code === 0) {
            alert(result.message || '操作成功');
            $('#myModal').modal('hide');

            // 清空表单
            document.getElementById('addCategoryForm').reset();
            document.getElementById('preview').src = '';
            document.getElementById('preview').style.display = 'none';
            document.querySelector('.plus-icon').style.display = 'block';

            // 移除编辑标志
            submitButton.removeAttribute("data-category-id");

            location.reload();
        } else {
            alert('操作失败：' + (result.message || '未知错误'));
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('提交失败，请稍后重试');
    });
}

function editCategory(id, name, description, coverUrl) {
    document.getElementById("myModalLabel").innerText = "编辑分类";
    document.getElementById("categoryname").value = name;
    document.getElementById("categorycontent").value = description;

    const preview = document.getElementById("preview");
    preview.src = coverUrl;
    preview.style.display = 'block';

    document.querySelector('.plus-icon').style.display = 'none';
    document.getElementById("submitcat").setAttribute("data-category-id", id);

    $('#myModal').modal('show');
}

function moveCategory(id,direction){
    fetch(`/end/moveCategory/${id}/${direction}`,{method:'POST'})
        .then(response=>{
            if(!response.ok){
                throw new Error('移动失败');
            }
            return response.json();
        })
        .then(result=>{
            if(result.code==0){
                location.reload();
            }else {
                alert(result.message || '移动失败');
            }
        })
        .catch(error=>{
            console.error('Error:',error);
            alert('操作失败，请稍后再试');
        });

}

function deleteCategory(id){
    alert('暂不支持删除分类！！！')
}
